package com.kekezu.kppw.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.tsz.afinal.FinalDb;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.kekezu.kppw.bean.CityBean;
import com.kekezu.kppw.utils.ConfigInc;
import com.kekezu.kppw.utils.HttpUtils;

public class CityData {
	static FinalDb db;

	/**
	 * 所有省市
	 * 
	 * @param context
	 */
	public static void getCity(Context context) {
		String urlString = ConfigInc.getServiceAdress(context)
				+ "task/district";
		HttpUtils httpUtils = HttpUtils.getInstance();
		try {
			String strJson = httpUtils.httpGet(urlString, context);
			JSONObject jsonObject = new JSONObject(strJson);
			String resString = jsonObject.getString("code");

			// 对返回的数据进行判断
			if (resString.equals("1000")) {
				db = ConfigInc.getCreateDB(context);
				CityBean cityBean = new CityBean();
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject itemJsonObject = jsonArray.optJSONObject(i);
					cityBean.setUpid(itemJsonObject.getInt("upid"));
					cityBean.setCid(itemJsonObject.getInt("id"));
					cityBean.setName(itemJsonObject.getString("name")
							.toString());
					cityBean.setName(itemJsonObject.getString("name")
							.toString());
					JSONArray cityArray = itemJsonObject.getJSONArray("child");

					db.save(cityBean);
					for (int j = 0; j < cityArray.length(); j++) {
						JSONObject city = cityArray.optJSONObject(j);

						cityBean.setUpid(city.getInt("upid"));
						cityBean.setCid(city.getInt("id"));
						cityBean.setName(city.getString("name").toString());

						db.save(cityBean);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跟pid查询城市
	 * 
	 * @param strPid
	 * @param context
	 * @return
	 */
	public static ArrayList<HashMap<String, Object>> getCityByPid(
			String strPid, Context context) {
		ArrayList<HashMap<String, Object>> cityList = new ArrayList<HashMap<String, Object>>();

		db = ConfigInc.getCreateDB(context);
		List<CityBean> cityBean = db.findAll(CityBean.class);

		for (int i = 0; i < cityBean.size(); i++) {
			if (cityBean.get(i).getUpid() == Integer.valueOf(strPid)) {
				HashMap<String, Object> map = new HashMap<String, Object>();

				map.put("cid", cityBean.get(i).getCid());
				map.put("name", cityBean.get(i).getName());

				cityList.add(map);
			}
		}
		return cityList;
	}
}
